package com.wiscamp.ninechapters.tags.infrastructure.mappers;

import com.wiscamp.ninechapters.tags.infrastructure.po.EntityPointPO;
import com.wiscamp.ninechapters.tags.infrastructure.po.KnowledgePointView;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Collection;

@Repository
public interface EntityPointMapper extends JpaRepository<EntityPointPO, Long>, JpaSpecificationExecutor<EntityPointPO> {
    @Query(value = "select e from EntityPointPO e where e.entityId = :entityId and e.primaryKeyId = :primaryKeyId and e.pointId = :pointId")
    EntityPointPO findEntityPoint(long entityId, long primaryKeyId, long pointId);

    @Query(value = "select distinct e.primaryKeyId from KnowledgePointPO t, EntityPointPO e where e.pointId = t.pointId and e.entityId = :entityId and e.pointId in (:pointIds) and t.enabled = true and t.deleted = false")
    Collection<Long> findPrimaryIdsByPoints(long entityId, Collection<Long> pointIds);

    @Query(value = "select count(e.primaryKeyId) from EntityPointPO e where e.entityId = :entityId and e.pointId = :pointId")
    Long countPrimaryIdsByPoint(long entityId, long pointId);

    @Query(value = "select e from KnowledgePointView e, EntityPointPO et where e.pointId = et.pointId and et.entityId = :entityId and et.primaryKeyId = :primaryKeyId and e.enabled = true")
    Collection<KnowledgePointView> findPointsByPrimaryId(long entityId, long primaryKeyId);

    @Query(value = "select e from KnowledgePointView e, EntityPointPO et where e.pointId = et.pointId and et.entityId = :entityId and et.primaryKeyId = :primaryId and e.enabled = true and et.isPrimary = :isPrimary")
    Collection<KnowledgePointView> findPointsByPrimaryId(long entityId, long primaryId, boolean isPrimary);

    @Query(value = "select distinct t from KnowledgePointView t, EntityPointPO e where t.enabled = true and t.deleted = false and e.pointId = t.pointId and e.entityId = :entityId and e.primaryKeyId in (:primaryKeyIds)")
    Collection<KnowledgePointView> findPointsByPrimaryIds(long entityId, Collection<Long> primaryKeyIds);
}